<script setup lang="ts">
// 自定义树形多级选择器
import { onMounted, ref, watch } from 'vue';
import { CascaderOption, CascaderValue, ElCascader } from 'element-plus'
interface IProps {
  // 获取级联选择结果的函数
  fetchfunc?: (query?: any) => Promise<CascaderOption[]> | CascaderOption[],
  options?: CascaderOption[],
  fetchparams?: any,
  modelValue: CascaderValue,
}
const props = withDefaults(defineProps<IProps>(), {
  fetchfunc: async () => [],
  fetchparams: () => ({}),
})
defineEmits(['update:modelValue'])
const listTree = ref<CascaderOption[]>([])

async function initEnv() {
  if (Array.isArray(props.options)) return listTree.value = props.options
  const { fetchparams, fetchfunc } = props
  listTree.value = await fetchfunc(fetchparams)
}
onMounted(() => {
  initEnv()
})
// 监听参数变化,变化后可以再次初始化分类参数
watch(() => props.fetchparams, initEnv, { deep: true })
watch(() => props.options, initEnv, { deep: true })
defineExpose({ listTree })
</script>
<template>
  <ElCascader :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" v-bind="$attrs"
    :options="listTree" />
</template>